package com.zenithmind.gateway.exception;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 通用异常处理策略
 * 处理所有其他类型的异常
 * 遵循策略模式：实现通用异常处理算法
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class GenericExceptionStrategy implements ExceptionHandlingStrategy {
    
    private final ErrorResponseBuilder errorResponseBuilder;

    @Override
    public boolean canHandle(Throwable ex) {
        // 通用策略可以处理所有异常
        return true;
    }

    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        log.error("处理通用异常", ex);
        
        return exchange.getResponse().writeWith(Mono.fromSupplier(() -> {
            errorResponseBuilder.setResponseHeaders(exchange.getResponse(), HttpStatus.INTERNAL_SERVER_ERROR);
            
            DataBuffer buffer = errorResponseBuilder.buildErrorResponse(
                exchange.getResponse(),
                HttpStatus.INTERNAL_SERVER_ERROR,
                "网关服务异常: " + ex.getMessage(),
                ex
            );
            
            return buffer;
        }));
    }

    @Override
    public int getOrder() {
        return Integer.MAX_VALUE; // 最低优先级，作为兜底策略
    }
}
